import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import BackendLayout from '@/layouts/BackendLayout.vue'
import FrontendLayout from '@/layouts/FrontendLayout.vue'

// 前台路由
const frontendRoutes = [
  {
    path: '/',
    name: 'frontend',
    redirect:'/home',
    component: FrontendLayout,
    meta: { requiresAuth: false },
    children:[
    {
      path:'/home',
      name:'Home',
      component: () => import('@/views/frontend/Home.vue'),
      meta: { requiresAuth: false }
    },
        

  {
    path: '/courses',
    name: 'CourseList',
    component: () => import('@/views/frontend/Courses.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/courses/:id',
    name: 'CourseDetail',
    component: () => import('@/views/frontend/CourseDetail.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: () => import('@/views/frontend/user/Favorites.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/frontend/user/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/learning-records',
    name: 'LearningRecords',
    component: () => import('@/views/frontend/user/LearningRecords.vue'),
    meta: { requiresAuth: true }
  }
        
    ]
  },
]

// 后台路由
const backendRoutes = [
  {
    path: '/back',
    component: BackendLayout,
    redirect: '/back/dashboard',
    meta: { requiresAdmin: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/backend/Dashboard.vue'),
        meta: { title: '仪表盘', requiresAdmin: true }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/backend/admin/UserList.vue'),
        meta: { title: '用户管理', requiresAdmin: true }
      },
      {
        path: 'categories',
        name: 'CategoryManagement',
        component: () => import('@/views/backend/admin/CategoryList.vue'),
        meta: { title: '课程分类管理', requiresAdmin: true }
      },
      {
        path: 'courses',
        name: 'CourseManagement',
        component: () => import('@/views/backend/admin/CourseList.vue'),
        meta: { title: '课程管理', requiresAdmin: true }
      },
      {
        path: 'courses/import',
        name: 'CourseImport',
        component: () => import('@/views/backend/admin/CourseImport.vue'),
        meta: { title: '课程批量导入', requiresAdmin: true }
      },
      {
        path: 'favorites',
        name: 'FavoriteManagement',
        component: () => import('@/views/backend/admin/FavoriteList.vue'),
        meta: { title: '收藏管理', requiresAdmin: true }
      },
      {
        path: 'reviews',
        name: 'ReviewManagement',
        component: () => import('@/views/backend/admin/ReviewList.vue'),
        meta: { title: '评价管理', requiresAdmin: true }
      },
      {
        path:'announcements',
        name:'AnnouncementManagement',
        component:()=>import('@/views/backend/admin/AnnouncementList.vue'),
        meta:{title:'公告管理', requiresAdmin: true}
      },
  
      {
        path: 'personInfo',
        meta: { requiresAuth: true },
        children: [
          {
            path: 'profile',
            name: 'UserProfile',
            component: () => import('@/views/backend/PersonInfo.vue'),
            meta: { title: '个人中心', requiresAdmin: true }
          }
        ]
      }
    ]
  }
]

// 认证相关路由
const authRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { title: '注册' }
  }
]

// 404路由
const notFoundRoute = {
  path: '/404',
  name: 'NotFound',
  component: () => import('@/views/error/404.vue'),
  meta: { 
    title: '404',
    requiresAuth: false
  }
}

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...frontendRoutes,
    ...backendRoutes,
    ...authRoutes,
    notFoundRoute,
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFoundFallback',
      redirect: { name: 'NotFound' }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 学习推荐系统`
  }

  const userStore = useUserStore()

  // 如果是访问404页面，直接放行
  if (to.name === 'NotFound' || to.name === 'NotFoundFallback') {
    next()
    return
  }

  // 检查是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth) && !userStore.isLoggedIn) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }

  // 检查后台管理页面权限
  if (to.matched.some(record => record.meta.requiresAdmin)) {
    if (!userStore.isLoggedIn) {
      // 未登录用户访问后台，重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    } else if (userStore.userInfo && userStore.userInfo.role !== 'ADMIN') {
      // 非管理员访问后台，重定向到前台首页
      next('/')
      return
    }
  }

  // 已登录用户的路由控制
  if (userStore.isLoggedIn) {
    // 处理登录页面访问
    if (to.path === '/login' || to.path === '/register' ) {
      next(userStore.isAdmin ? '/back/dashboard' : '/')
      return
    }

    // 其他页面放行
    next()
  } else {
    // 未登录用户
    next()
  }
})

export default router
